import { useRef, useEffect, useMemo } from "react";
import { List } from "@/components/list";
import * as echarts from "echarts";

export const TotalCard = ({ dataSource, days, orderStatistics }) => {
  const ref = useRef(null);

  const echartsData = useMemo(() => {
    return orderStatistics?.map((item) => ({
      value: item?.amt,
      name: item?.storeName,
    }));
  }, [orderStatistics]);

  const initEcharts = () => {
    if (!ref.current) return;
    const myChart = echarts.init(ref.current);
    const option = {
      backgroundColor: "transparent",
      series: [
        {
          type: "pie",
          radius: ["45%", "60%"],
          center: ["50%", "50%"],
          data: echartsData.map((item, index) => ({
            ...item,
            itemStyle: {
              color: ["#1890ff", "#bae7ff", "#69c0ff", "#91d5ff", "#bae7ff"][
                index
              ],
              borderWidth: 12,
              borderRadius: 24,
            },
          })),
          itemStyle: {
            borderWidth: 12,
          },
          label: {
            show: true,
            position: "outside",
            formatter: "{b}\n{c}元",
            fontSize: 12,
            color: "#000",
            fontWeight: "bold",
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 5,
            lineStyle: {
              color: "#ccc",
            },
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
      tooltip: {
        trigger: "item",
        formatter: "{b}: {c}元 ({d}%)",
      },
    };

    myChart.setOption(option);

    // 响应式处理
    const resizeHandler = () => {
      myChart.resize();
    };

    window.addEventListener("resize", resizeHandler);

    return () => {
      window.removeEventListener("resize", resizeHandler);
      myChart.dispose();
    };
  };

  useEffect(() => {
    const cleanup = initEcharts();
    return cleanup;
  }, [orderStatistics]);

  return (
    <div className="total-card">
      <div className="total-card-title" />
      <div className="total-card-box">
        <div className="total-card-box-title">
          <div className="total-card-box-title-left">累计已省</div>
          <div className="total-card-box-title-right">
            我们一起携手度过了{days || 0}天省钱日子
          </div>
        </div>
      </div>
      <div className="total-card-box-title-right-echarts" ref={ref}></div>
      <div className="divider"></div>
      <div className="latest-save-money">最新一笔省钱</div>
      <List data={[dataSource]} />
    </div>
  );
};
